package orma

import (
	"github.com/go-xorm/xorm"
)

type (
	//XTransaction 支持事务
	XTransaction interface {
		SetSession(sn *xorm.Session)
		Session() *xorm.Session
	}

	//具有初始化数据的模型
	XInitData interface {
		InitData() interface{}
	}

	//所有拥有密码属性的表
	TableWithPassword interface {
		PasswordFieldName() string
		SetPassword(pwd string)
		VerifyPassword(plaintext string) error
	}

	BaseModel struct {
		ID      int64     `json:"id,omitempty" xorm:"autoincr pk"`
		Created *JSONTime `json:"created,omitempty" xorm:"notnull created index"`
		Updated *JSONTime `json:"updated,omitempty" xorm:"notnull updated"`
		Version int64     `json:"version,omitempty" xorm:"notnull version index"`

		engine     *xorm.Engine  `xorm:"-"`
		ormSession *xorm.Session `xorm:"-"`
	}
)

func (m *BaseModel) BeforeSet(name string, cell xorm.Cell) {
	if name == "created" || name == "Created" {
		m.Created = &JSONTime{}
	}
	if name == "updated" || name == "Updated" {
		m.Updated = &JSONTime{}
	}
}

func (m *BaseModel) SetSession(sn *xorm.Session) {
	m.ormSession = sn
}

func (m *BaseModel) Session() *xorm.Session {
	var sn = m.ormSession
	if m.ormSession == nil {
		sn = engine.NoCache()
	}
	return sn
}
